const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); //打包压缩
const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 压缩为gzip
const productionGzipExtensions = ["js", "css"];

// 正式包配置
function proConfig(config) {
  return () => {
    config
      .plugin("uglifyjs-plugin")
      .use("uglifyjs-webpack-plugin", [
        {
          uglifyOptions: {
            warnings: false,
            parse: {},
            compress: {
              properties: true, //用.来重写属性引用，例如foo["bar"] → foo.bar
              sequences: true, //续声明变量，用逗号隔开来
              dead_code: true, //移除没被引用的代码
              conditionals: true, //优化if等判断以及条件选择
              booleans: true, //优化布尔运算
              unused: true, //优化布尔运算
              if_return: true, //优化 if/return 和 if/continue
              join_vars: true, //合并连续 var 声明
              drop_console: true, //移除 console
              drop_debugger: true, //移除 debugger
            },
            mangle: true,
            output: null,
            toplevel: false,
            nameCache: null,
            ie8: false,
            keep_fnames: false,
            beautify: true,
          },
        },
      ])
      .end();
  };
}

module.exports = {
  outputDir: process.env.VUE_APP_OUTPUTDIR, // 打包生成目录
  // devServer: {
  //     open: true,
  //     port: 8080,
  //     disableHostCheck: true,
  // },
  devServer: {
    open: true,
    proxy: {
      // 配置跨域
      "/api": {
        // target: `http://webpage-games.imobybox.com`, //请求后台接口
        // target: `https://api.weslots.cc`,
        target: `https://test-api.weslots.cc`,
        // target: `https://api.luckwin365.cc`,
        changeOrigin: true, // 允许跨域
        pathRewrite: {
          "^/api": "", // 重写请求
        },
      },
    },
  },
  assetsDir: "assets", // 打包后静态文件存储位置
  productionSourceMap: false, //删除map
  configureWebpack: {
    // webpack 配置
    optimization: {
      splitChunks: {
        automaticNameDelimiter: "-", //包切割时把~替换为 -
      },
      minimizer: [
        new UglifyJsPlugin({
          cache: true, //启用缓存 因为添加了版本号,不用考虑生产环境缓存问题
          parallel: true, //使用多进程并行运行来提高构建速度
          sourceMap: false, //不生成map
        }),
      ],
    },
    plugins: [
      new CompressionWebpackPlugin({
        algorithm: "gzip",
        test: new RegExp("\\.(" + productionGzipExtensions.join("|") + ")$"),
        threshold: 10240,
        minRatio: 0.8,
      }),
    ],
  },
  chainWebpack: (config) => {
    process.env.VUE_APP_ENV == "prod" && proConfig(config)();
    process.env.VUE_APP_ENV == "test" && proConfig(config)();
  },
};
